package cn.sylinx.common.ext.web;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URI;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.sylinx.common.ext.log.GLog;

public class HttpClient4PlusUtil {

	public static interface DownloadCallback {
		void exe(String fileName, byte[] content);
	}

	/**
	 * 下载附件
	 * 
	 * @param url
	 * @return @throws
	 */
	public static void getFile(String url, DownloadCallback cb) {

		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpGet method = new HttpGet(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000).build();// 设置请求和传输超时时间
		method.setConfig(requestConfig);

		try {

			response = httpClient.execute(method);

			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {

				HttpEntity entity = response.getEntity();
				Header header = response.getLastHeader("Content-Disposition");
				String vl = header.getValue();
				int index = vl.lastIndexOf(".");
				String postfix = ".download";
				// 获取媒体文件后缀
				if (index > 0) {
					postfix = vl.substring(index, vl.length() - 1);
				}
				String fileName = System.currentTimeMillis() + postfix;

				InputStream in = entity.getContent();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = in.read(buffer)) != -1) {
					baos.write(buffer, 0, len);
				}
				baos.flush();
				baos.close();

				EntityUtils.consume(entity);
				cb.exe(fileName, baos.toByteArray());

			} else {
				GLog.error("获取到意外返回码：", statusCode);
			}

		} catch (Exception e) {
			GLog.error("调用接口异常", e);

		} finally {

			HttpClientUtils.closeQuietly(httpClient);
			HttpClientUtils.closeQuietly(response);
		}
	}

	public static String getWithString(String url) {

		String result = null;

		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpGet method = new HttpGet(url);
		
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).build();// 设置请求和传输超时时间
		method.setConfig(requestConfig);
		try {
			response = httpClient.execute(method);

			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity, "UTF-8");
				EntityUtils.consumeQuietly(entity);
			} else {
				GLog.error("获取到意外返回码：", statusCode);
			}

		} catch (Exception e) {

			GLog.error("调用接口异常", e);

		} finally {

			HttpClientUtils.closeQuietly(httpClient);
			HttpClientUtils.closeQuietly(response);
		}

		return result;
	}

	public static JSONObject getWithJson(String url) {

		JSONObject json = new JSONObject();
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpGet method = new HttpGet(url);

		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).build();// 设置请求和传输超时时间
		method.setConfig(requestConfig);

		try {
			response = httpClient.execute(method);

			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				String result = EntityUtils.toString(entity, "UTF-8");
				json = (JSONObject) JSON.parse(result);
				EntityUtils.consumeQuietly(entity);
			} else {
				GLog.error("获取到意外返回码：", statusCode);
			}

		} catch (Exception e) {

			GLog.error("调用接口异常", e);
			json.put("errcode", "5000");
			json.put("errmsg", "调用接口异常");

		} finally {

			HttpClientUtils.closeQuietly(httpClient);
			HttpClientUtils.closeQuietly(response);
		}

		return json;
	}

	public static JSONObject post(String api, String json) {

		JSONObject jsonObject = new JSONObject();

		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;

		HttpPost method = new HttpPost();
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).build();// 设置请求和传输超时时间
		method.setConfig(requestConfig);

		try {
			URI base = new URI(api);
			method.setURI(base);
			method.setHeader("Content-Type", "application/json;charset=UTF-8");
			StringEntity se = new StringEntity(json, "UTF-8");
			method.setEntity(se);
			response = httpClient.execute(method);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {

				HttpEntity entity = response.getEntity();
				String result = EntityUtils.toString(entity, "UTF-8");
				jsonObject = (JSONObject) JSON.parse(result);
				EntityUtils.consumeQuietly(entity);

			} else {
				GLog.error("获取到意外返回码：", statusCode);
			}

		} catch (Exception e) {

			GLog.error("调用接口异常", e);
			jsonObject.put("errcode", "5000");
			jsonObject.put("errmsg", "调用接口异常");

		} finally {

			HttpClientUtils.closeQuietly(httpClient);
			HttpClientUtils.closeQuietly(response);
		}

		return jsonObject;
	}

	public static JSONObject upload(String url, File file) {

		JSONObject ja = new JSONObject();
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000).build();// 设置请求和传输超时时间
		httpPost.setConfig(requestConfig);
		CloseableHttpResponse response = null;

		try {

			MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
			mEntityBuilder.addBinaryBody(file.getName(), file);
			httpPost.setEntity(mEntityBuilder.build());
			response = httpclient.execute(httpPost);

			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {

				HttpEntity resEntity = response.getEntity();
				String result = EntityUtils.toString(resEntity);
				ja = (JSONObject) JSON.parse(result);
				// 消耗掉response
				EntityUtils.consume(resEntity);
			} else {
				GLog.error("获取到意外返回码：", statusCode);
			}

		} catch (Exception e) {
			GLog.error("上传文件失败：", e);
			ja.put("errcode", "5000");
			ja.put("errmsg", "调用接口异常");

		} finally {
			HttpClientUtils.closeQuietly(httpclient);
			HttpClientUtils.closeQuietly(response);
		}

		return ja;
	}
}
